const express = require('express');
const router = express.Router();
const SMSClient = require("@alicloud/sms-sdk");
const ModuleDate = require('../../databases/model')

/* GET users listing. */
router.get('/', function (req, res, next) {
  const find = ModuleDate.UserModel.find()
  console.log(find, req.query)
  res.send('respond with a resource');
});


router.post('/login', async function (req, res, next) {
  const { studentId, password } = req.body
  console.log(studentId, password)
  const find = await ModuleDate.UserModel.findOne({ studentId: studentId, password: password })
  console.log(find)
  if (find) {
    res.send({
      code: 200,
      message: '登录成功',
      data: find
    })
  } else {
    res.send({
      code: 400,
      message: '登录失败'
    })
  }
});

router.get('/data', async function (req, res) {
  let data = await ModuleDate.CoursesModel.find()
  res.send({
    code: 200,
    data: data
  })
})
router.post('/recommend', async function (req, res) {
  const { id } = req.body
  const find = await ModuleDate.CoursesModel.find({ _id: id })
  if (find.status == 0) {
    await ModuleDate.CoursesModel.updateOne({ _id: id }, { $set: { status: 1 } })
    res.send({
      code: 200,
      message: '预约成功',
      data: find,
    })
  } else {
    await ModuleDate.CoursesModel.updateOne({ _id: id }, { $set: { status: 0 } })
    res.send({
      code: 200,
      message: '取消预约成功',
      data: find,
    })
  }
}
)

router.get("/list", async function (req, res) {
  const { course, page } = req.query
  const pageSize = 20

  const data = await ModuleDate.DataModel.find({ course }).skip((page - 1) * pageSize).limit(pageSize)
  const total = await ModuleDate.DataModel.countDocuments({ course })
  res.send({
    code: 200,
    data: data,
    total: total
  })
})

// 1. 收藏题目
router.post('/collect', async (req, res) => {
  try {
    const { questionId } = req.body;  // 从请求体获取题目ID
    const userId = req.user._id;      // 假设您已经设置了用户认证

    if (!questionId) {
      return res.json({
        success: false,
        message: '题目ID不能为空'
      });
    }

    await UserModel.findByIdAndUpdate(userId, {
      $addToSet: { collection: questionId }
    });

    res.json({
      success: true,
      message: '收藏成功'
    });
  } catch (error) {
    res.json({
      success: false,
      message: error.message
    });
  }
});

// 2. 取消收藏
router.post('/uncollect', async (req, res) => {
  try {
    const { questionId } = req.body;
    const userId = req.user._id;

    if (!questionId) {
      return res.json({
        success: false,
        message: '题目ID不能为空'
      });
    }

    await UserModel.findByIdAndUpdate(userId, {
      $pull: { collection: questionId }
    });

    res.json({
      success: true,
      message: '取消收藏成功'
    });
  } catch (error) {
    res.json({
      success: false,
      message: error.message
    });
  }
});

// 3. 检查题目是否已被收藏
router.post('/checkCollection', async (req, res) => {
  try {
    const { questionId } = req.body;
    const userId = req.user._id;

    if (!questionId) {
      return res.json({
        success: false,
        message: '题目ID不能为空'
      });
    }

    const user = await UserModel.findById(userId);
    const isCollected = user.collection.includes(questionId);

    res.json({
      success: true,
      isCollected: isCollected
    });
  } catch (error) {
    res.json({
      success: false,
      message: error.message
    });
  }
});

// 4. 获取用户所有收藏的题目
router.get('/getCollections', async (req, res) => {
  try {
    const userId = req.user._id;

    const user = await UserModel.findById(userId);
    const collectedQuestions = await DataModel.find({
      _id: { $in: user.collection }
    });

    res.json({
      success: true,
      data: collectedQuestions
    });
  } catch (error) {
    res.json({
      success: false,
      message: error.message
    });
  }
});

// 发送短信验证码
const accessKeyId = "LTAI5t84kUFyT3ugLZNkPuHw"; // 替换为你的 AccessKey ID
const secretAccessKey = "ooeBxbdw1VsvnWVxb6YVQwQksTct5C"; // 替换为你的 AccessKey Secret
const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
// 发送短信验证码的接口
router.post("/code", async (req, res) => {
  let { phone } = req.body;

  if (!phone) {
    return res.status(400).json({ success: false, message: "手机号不能为空" });
  }
  // 生成随机验证码
  const code = Math.floor(100000 + Math.random() * 900000).toString();
  try {
    // 调用阿里云短信服务
    const result = await smsClient.sendSMS({
      PhoneNumbers: phone, // 目标手机号
      SignName: "阿里云短信测试", // 短信签名（需与阿里云控制台一致）
      TemplateCode: "SMS_154950909", // 短信模板CODE（需与阿里云控制台一致）
      TemplateParam: `{"code":"${code}"}`, // 短信模板中的变量
    });
    console.log("阿里云返回结果:", JSON.stringify(result, null, 2)); // 打印阿里云返回的结果
    if (result.Code === "OK") {
      // 验证码发送成功
      console.log(`验证码已发送至 ${phone}，验证码为：${code}`);
      res.send({ success: true, message: "验证码发送成功",code:code });//将生成的验证码返回给前端
    } else {
      // 发送失败
      console.error("短信发送失败:", result.Message);
      res.status(500).json({
        success: false,
        message: "短信发送失败",
        error: result.Message,
      });
    }
  } catch (error) {
    console.error("短信服务异常:", error.message);
    res.json({ success: false, message: "验证码发送失败", })//返回给前端错误
    res .status(500)  .json({ success: false, message: "短信服务异常", error: error.message });
  }
});
module.exports = router;